package com.violet.uaa.server.security.handler;

import cn.hutool.json.JSONUtil;
import com.violet.common.constant.business.CodeEnum;
import com.violet.common.response.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 类说明:spring security 登录成功但权限不足处理
 *
 * @author wqf
 * @date 2022/6/14 14:18
 */
@Component
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try (ServletOutputStream ous = response.getOutputStream()) {
            Result<Object> responseData = Result.failure(CodeEnum.FORBIDDEN.getCode(), "暂无权限，请联系管理员");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            ous.write(JSONUtil.toJsonStr(responseData).getBytes(StandardCharsets.UTF_8));
        }
    }
}

